package com.huo15.uniplugin_trtc;

import static com.tencent.trtc.TRTCCloudDef.TRTCRoleAnchor;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSONObject;
import com.huo15.uniplugin_trtc.util.PermissionUtil;
import com.tencent.liteav.TXLiteAVCode;
import com.tencent.liteav.device.TXDeviceManager;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
import com.tencent.trtc.debug.GenerateTestUserSig;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import io.dcloud.feature.uniapp.UniSDKInstance;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.ui.action.AbsComponentData;
import io.dcloud.feature.uniapp.ui.component.AbsVContainer;
import io.dcloud.feature.uniapp.ui.component.UniComponent;

import android.os.Bundle;
import android.net.Uri;

public class Huo15CameraView extends UniComponent<TXCloudVideoView> {
    String TAG = "Huo15CameraView";
    protected static final int REQ_PERMISSION_CODE = 0x1000;
    private int mUserCount = 0;
    private List<String> mRemoteUidList;
    private List<TXCloudVideoView> mRemoteViewList;
    private TXDeviceManager mTXDeviceManager;
    Activity activity;
    private TRTCCloud mTRTCCloud;
    private boolean mIsFrontCamera = true;
    private int REQUEST_CODE_MIC_SETTING_PERMISSION = 0x1001;

    public Huo15CameraView(UniSDKInstance instance, AbsVContainer parent, AbsComponentData basicComponentData) {
        super(instance, parent, basicComponentData);
        activity = (Activity) mUniSDKInstance.getContext();
    }

    @Override
    protected TXCloudVideoView initComponentHostView(@NonNull Context context) {
        // 启动本地摄像头的预览（localCameraVideo 是用于渲染本地渲染画面的控件）
        TXCloudVideoView cameraVideo = new TXCloudVideoView(context);

        return cameraVideo;
    }

    @UniJSMethod
    public void enterRoom(JSONObject options) {

        if (!checkPermission()) {
            Log.e(TAG, "没有权限");
            return;
        }
        Log.d(TAG, "enterRoom---" + options.toString());
        mTRTCCloud = TRTCCloud.sharedInstance(activity.getApplicationContext());
        mTRTCCloud.setListener(new TRTCCloudImplListener(activity));
        String userId = (String) options.get("userId");
        Integer roomId = (Integer) options.get("roomId");
        Log.d(TAG, "userId: " + userId + " roomId: " + roomId);
        // 获取包管理器实例
        PackageManager packageManager = activity.getPackageManager();
        // 获取应用程序信息
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "无法找到应用程序信息:" + e.getMessage());
            throw new RuntimeException("无法找到应用程序信息", e);
        }
        // 获取meta-data
        Bundle metaData = applicationInfo.metaData;
        // 通过键获取值
//        String sdkAppId = metaData.getString("sdkappid");
        String sdkAppId = "1600009875";

        TRTCCloudDef.TRTCParams trtcParams = new TRTCCloudDef.TRTCParams();
        trtcParams.sdkAppId = Integer.parseInt(sdkAppId);
        trtcParams.userId = String.valueOf(userId);
        trtcParams.roomId = (int) roomId;
        trtcParams.userSig = GenerateTestUserSig.genTestUserSig(trtcParams.userId);
        mTRTCCloud.startLocalPreview(mIsFrontCamera, getHostView());
        mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH);
        mTRTCCloud.enterRoom(trtcParams, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);

    }

    @UniJSMethod
    public void exitRoom() {
        if (mTRTCCloud != null) {
            mTRTCCloud.stopLocalAudio();
            mTRTCCloud.stopLocalPreview();
            mTRTCCloud.exitRoom();
            mTRTCCloud.setListener(null);
        }
        mTRTCCloud = null;
        TRTCCloud.destroySharedInstance();
    }

    protected boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat
                    .checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat
                    .checkSelfPermission(activity, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat
                    .checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat
                    .checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(activity, permissions.toArray(new String[0]),
                        REQ_PERMISSION_CODE);
                return false;
            }
        }
        return true;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE_MIC_SETTING_PERMISSION == requestCode) {
            Log.v(TAG, "onActivityResult REQUEST_CODE_MIC_SETTING_PERMISSION");
//            dismissMicDialog();
            //从系统页面返回再次获取当前mic权限是否授予
            boolean hasAudioPermission = PermissionUtil.checkPermission(activity, Manifest.permission.RECORD_AUDIO, REQUEST_CODE_MIC_SETTING_PERMISSION);
            Log.v(TAG, "onActivityResult hasAudioPermission: " + hasAudioPermission);
            if (hasAudioPermission) {
                showPermissionOnToast();
            } else {
                showPermissionOffToast();
            }
        }
    }

    private void showPermissionOnToast() {
        Toast.makeText(activity, "麦克风权限开启成功", Toast.LENGTH_SHORT).show();
    }

    private void showPermissionOffToast() {
        Toast.makeText(activity, "麦克风权限开启失败", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQ_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                String preName = permissions[i];
                int granted = grantResults[i];
                Log.d(TAG, "权限名称：" + preName + ", granted=" + granted);
            }


        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private class TRTCCloudImplListener extends TRTCCloudListener implements com.huo15.uniplugin_trtc.TRTCCloudImplListener {

        private WeakReference<Activity> mContext;

        public TRTCCloudImplListener(Activity activity) {
            super();
            mContext = new WeakReference<>(activity);
        }

        @Override
        public void onUserVideoAvailable(String userId, boolean available) {
            Log.d(TAG,
                    "onUserVideoAvailable userId " + userId + ", mUserCount " + mUserCount + ",available " + available);
            int index = mRemoteUidList.indexOf(userId);
            if (available) {
                if (index != -1) {
                    return;
                }
                mRemoteUidList.add(userId);
                refreshRemoteVideoViews();
            } else {
                if (index == -1) {
                    return;
                }
                mTRTCCloud.stopRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG);
                mRemoteUidList.remove(index);
                refreshRemoteVideoViews();
            }

        }

        private void refreshRemoteVideoViews() {
            for (int i = 0; i < mRemoteViewList.size(); i++) {
                if (i < mRemoteUidList.size()) {
                    String remoteUid = mRemoteUidList.get(i);
                    mRemoteViewList.get(i).setVisibility(View.VISIBLE);
                    mTRTCCloud.startRemoteView(remoteUid, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,
                            mRemoteViewList.get(i));
                } else {
                    mRemoteViewList.get(i).setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onError(int errCode, String errMsg, Bundle extraInfo) {
            Log.d(TAG, "sdk callback onError");
            Activity activity = mContext.get();
            if (activity != null) {
                Toast.makeText(activity, "onError: " + errMsg + "[" + errCode + "]", Toast.LENGTH_SHORT).show();
                if (errCode == TXLiteAVCode.ERR_ROOM_ENTER_FAIL) {
                    exitRoom();
                }
            }
        }
    }
}
